/*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.hisense.settings;
import android.app.AlertDialog.Builder;
import com.android.settings.SettingsPreferenceFragment;
import com.google.android.tv.settings.TvSettings;
import com.hisense.settings.util.TvIntents;
import com.hisense.settings.util.Wrapper;
import com.android.settings.DisplaySettings;
import static com.google.android.tv.settings.TvSettings.System.SCREEN_DIM_TIMEOUT;
import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT;
import static android.provider.Settings.System.SOUND_EFFECTS_ENABLED;
import com.android.settings.R;
//import com.google.tv.avapi.AudioOutput;
//import com.google.tv.avapi.TvMode;
//import com.google.tv.avapi.AudioOutput.Mode;
//import com.google.tv.avapi.TvMode.DisplayMode;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.PreferenceScreen;
import android.text.TextUtils.SimpleStringSplitter;
import android.util.Log;
import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT;
import static android.provider.Settings.System.SOUND_EFFECTS_ENABLED;

import android.content.ComponentName;
import android.media.AudioManager;
import android.view.WindowManager;
import android.preference.ListPreference;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.content.SharedPreferences;

import java.util.HashSet;
import java.util.List;
import java.util.Set;


public class LocalSettings extends SettingsPreferenceFragment {
    private static final String TAG = "LocalSettings";
	
	private static AlertDialog        localDialog = null;
	
	private static final String KEY_CC_SETTINGS = "cc_settings";
	private static final String KEY_BOOT_WIZARD = "boot_wizard";
	private static final String KEY_E_MANUAL = "manual";
	public static final String KEY_CHECKBOX_RETAIL = "retail_mode_switch";
	private static final String KEY_SOTORE_MODE_ENABLE = "store_mode_enable";
	
	private static final int DYNAMIC_NOISEREDUCTION_HIGH = 3;
	private static final int DYNAMIC_CONTRAST = 1;
	private static final int DYNAMIC_BACKLIGHT = 1;

	private static final int COLORTEMPERATURE_MODE_NORMAL = 0;
	private static final int COLORTEMPERATURE_MODE_WARM = 2;
	private static final int COLORTEMPERATURE_MODE_COOL = 1;

	private static final int DYNAMICNOISE_MODE_OFF = 0;
	private static final int DYNAMICNOISE_MODE_LOW = 1;
	private static final int DYNAMICNOISE_MODE_MEDIUM = 2;
	private static final int DYNAMICNOISE_MODE_HIGH = 3;

	private static final int IMAGE_MODE_RESET_VALUE = 0;
	private static final int IMAGE_MODE_STANDARD = 0;
	private static final int IMAGE_MODE_VIVID = 1;
	private static final int IMAGE_MODE_GAME = 4;
	private static final int IMAGE_MODE_THEATER = 3;
	private static final int IMAGE_MODE_ENERGYSAVING = 6;
	private static final int IMAGE_MODE_CUSTOM = 7;

	private static final int VALUE_DYNAMIC_CONTRAST_ON = 1;
	private static final int VALUE_DYNAMIC_CONTRAST_OFF = 0;	
	private static final int VALUE_DYNAMIC_BACKLIGHT_ON = 1;
	private static final int VALUE_DYNAMIC_BACKLIGHT_OFF = 0;

	private static final int DIALOG_GOTO_BOOTWIZARD = 2234;//bwd
	private static final int DIALOG_STORE_MODE = 128;
	PreferenceScreen mBootWizardpPreference;
	PreferenceScreen mEmanualPreference;
	private CheckBoxPreference checkboxRetailMode;

	private SharedPreferences mSharedPrefs;
//	private PowerDataGettings mGetRetailModeOldValue;
	private String mOldImageMode;
	private String mDynamicNoiseMode;
	private String mBacklightMode;
	private String mDynamicContradtMode;
	private PreferenceScreen mCloseCaptionCC;
	private boolean isTuner = false;
	private Wrapper mWrapper = null;
	private Context mContext = null;
	private static final String INTENT_EXTRA_FORCED = "forced";
	private static final String mEposAccessibilityService = 
			"com.marvell.willowtv.controller/com.hisense.gtv.controller.EPosAccessibilityService";
	private static final Set<ComponentName> sInstalledServices = new HashSet<ComponentName>();
	// Auxiliary members.
	private static final char ENABLED_ACCESSIBILITY_SERVICES_SEPARATOR = ':';
    private final static SimpleStringSplitter sStringColonSplitter =
            new SimpleStringSplitter(ENABLED_ACCESSIBILITY_SERVICES_SEPARATOR);
			
	//private Picture picture;
	private BroadcastReceiver mEventReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if(action.equals(TvIntents.INTENT_SOURCE_BIND_CHANGE)){
				isTuner = Wrapper.getWrapperInstance().isTunerInput();
				MyLog.d(TAG, "isTuner:"+isTuner);
				mCloseCaptionCC.setEnabled(isTuner);
			}
			
		}};
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
		getActivity().setTitle(R.string.local_settings);
        mContext = getActivity();
		mWrapper = Wrapper.getWrapperInstance();
		mWrapper.setContext(mContext);
        addPreferencesFromResource(R.xml.local_settings);
        
        mBootWizardpPreference = (PreferenceScreen) findPreference(KEY_BOOT_WIZARD);
		mEmanualPreference = (PreferenceScreen) findPreference(KEY_E_MANUAL);
		removePreference(KEY_E_MANUAL);
		checkboxRetailMode = (CheckBoxPreference) findPreference(KEY_CHECKBOX_RETAIL);

		setupRetailMode();

		mCloseCaptionCC=(PreferenceScreen) findPreference(KEY_CC_SETTINGS);
		//picture = TvFramework.getInstance().getPictureInstance();
		//add for refresh CC
		IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(TvIntents.INTENT_SOURCE_BIND_CHANGE);

        mContext.registerReceiver(mEventReceiver, intentFilter);
    }


 @Override
	public void onResume() {
		super.onResume();
		isTuner = Wrapper.getWrapperInstance().isTunerInput();
		MyLog.d(TAG, "isTuner:"+isTuner);
		mCloseCaptionCC.setEnabled(isTuner);
	}

 
	@Override
	public void onPause() {
	super.onPause();
	
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		if(mEventReceiver!=null){
			mContext.unregisterReceiver(mEventReceiver);
		}
	}


	private void setupRetailMode() {
        checkboxRetailMode.setPersistent(true);

		//refresh bootwizard's setting
		boolean storeMode = TvSettings.Secure.getBoolean(getContentResolver(),
                    KEY_SOTORE_MODE_ENABLE,false);	
		MyLog.d(TAG, "storeMode:"+storeMode);
		if (storeMode){
			checkboxRetailMode.setChecked(true);
			//setEposMode();
		}	   
		else {
			checkboxRetailMode.setChecked(false);
			//resetEposMode();
		}
		//onPreferenceToggled(mEposAccessibilityService,storMode);
        checkboxRetailMode.setOnPreferenceClickListener(
                new Preference.OnPreferenceClickListener() {
            public boolean onPreferenceClick(Preference preference) {
                boolean enabled = checkboxRetailMode.isChecked();
				TvSettings.Secure.putBoolean(getContentResolver(),KEY_SOTORE_MODE_ENABLE, enabled);
                if (enabled) {
				showDialog();
//                    setRetailMode();
                } else {
                	MyLog.d(TAG, "resetRetailMode&resetEposMode");
                	resetRetailMode();
                	resetEposMode();
                	//picture.setRetailMode(false);
                }
				
                return true;
            }
        });
    }
	
	private void setRetailMode() {	
		setImageMode(IMAGE_MODE_VIVID);
	}
	
	private void resetRetailMode() {

		int value = 0;
		setImageMode(IMAGE_MODE_ENERGYSAVING);	
	}
    private void setImageMode(int imageMode) {
		Wrapper.getWrapperInstance().setPictureMode(imageMode);				
    }
	private void setEposMode() {
		//com.google.android.marvin.talkback/com.google.android.marvin.talkback.TalkBackService
		Settings.Secure.putString(getContentResolver(),
		Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES,
		"com.marvell.willowtv.controller/com.hisense.gtv.controller.EPosAccessibilityService");
		Settings.Secure.putInt(getContentResolver(),
                Settings.Secure.ACCESSIBILITY_ENABLED, 1);
	}
	private void resetEposMode() {
		 /*String enabledServicesSetting = Settings.Secure.getString(mContext.getContentResolver(),
	                Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
		 if(enabledServicesSetting!=null&&enabledServicesSetting.contains("talkback")){
			 Settings.Secure.putString(getContentResolver(),
	                    Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES,
	                    "");
			 Settings.Secure.putInt(getContentResolver(),Settings.Secure.ACCESSIBILITY_ENABLED, 0);
			 Settings.Secure.putString(getContentResolver(),
	                    Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES,
	                    "com.google.android.marvin.talkback/com.google.android.marvin.talkback.TalkBackService");
			 Settings.Secure.putInt(getContentResolver(),Settings.Secure.ACCESSIBILITY_ENABLED, 1);
		 }else{*/
			 Settings.Secure.putString(getContentResolver(),
	                    Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES,
	                    "");
			 Settings.Secure.putInt(getContentResolver(),Settings.Secure.ACCESSIBILITY_ENABLED, 0);
		 //}
	
	}	

	private boolean showDialog(){
            final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity())
            //.setIconAttribute(android.R.attr.alertDialogIcon)
			.setCancelable(false)
            .setTitle(R.string.picture_mode)
            .setMessage(R.string.retail_mode_message)
				
            .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    /* User clicked OK so do some stuff */
					setRetailMode();
					setEposMode();
					MyLog.d(TAG, "onCreateDialog " + "setStoreMode(true)");
					TvSettings.Secure.putBoolean(getContentResolver(),KEY_SOTORE_MODE_ENABLE, true);
					boolean data = TvSettings.Secure.getBoolean(getContentResolver(),
	                KEY_SOTORE_MODE_ENABLE,false);
					//picture.setRetailMode(data);	
					MyLog.d(TAG,"StoreMode " + (data ? 1 : 0));
                }
            })
            .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
					checkboxRetailMode.setChecked(false);
                    /* User clicked Cancel so do some stuff */					
					Log.d(TAG, "onCreateDialog " + "setStoreMode(false)");
					TvSettings.Secure.putBoolean(getContentResolver(),KEY_SOTORE_MODE_ENABLE, false);
					boolean data = TvSettings.Secure.getBoolean(getContentResolver(),
	                KEY_SOTORE_MODE_ENABLE,false);
					//picture.setRetailMode(data);
					MyLog.d(TAG, "StoreMode " + (data ? 1 : 0));						
                }
            });
			localDialog=builder.create();			
			localDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
			localDialog.show();				
            return false;
        }
			
	public Dialog onCreateDialog(int id) {
        switch (id) {
            case DIALOG_GOTO_BOOTWIZARD: {
                final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity())
                //.setIconAttribute(android.R.attr.alertDialogIcon)
                .setTitle(R.string.boot_wizard)
                .setMessage(R.string.boot_wizard_reload)
                .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        /* User clicked OK so do some stuff */
						Intent intent = new Intent("com.google.android.tv.intent.action.SETUP");
						intent.putExtra(INTENT_EXTRA_FORCED, true);
						startActivity(intent);
                    }
                })
                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                        /* User clicked Cancel so do some stuff */
                    }
                });


                return builder.create();
            }
			
            default:
                break;
        }
        return super.onCreateDialog(id);
    }	

	 @Override
	    public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
			if (preference == mBootWizardpPreference) {
				showDialog(DIALOG_GOTO_BOOTWIZARD);
			} 
			/*else if (preference == mEmanualPreference){
				try {
					Intent intent = new Intent();   
				    intent.setComponent(new ComponentName("com.hisense.emanual","com.hisense.emanual.MainActivity"));   
		    		intent.setAction(Intent.ACTION_VIEW);  			 
					startActivity(intent);
					
				} catch (ActivityNotFoundException e) {
					MyLog.e(TAG, "Activity Not Found!");
					e.printStackTrace();
				}			
			}*/
	        return false;
	    }

	    public boolean onPreferenceChange(Preference preference, Object objValue) {
	        final String key = preference.getKey();

	        return true;
	    }

	    //the following is add for Epos
	    private static Set<ComponentName> getEnabledServicesFromSettings(Context context) {
	        String enabledServicesSetting = Settings.Secure.getString(context.getContentResolver(),
	                Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
	        if (enabledServicesSetting == null) {
	            enabledServicesSetting = "";
	        }
	        Set<ComponentName> enabledServices = new HashSet<ComponentName>();
	        SimpleStringSplitter colonSplitter = sStringColonSplitter;
	        colonSplitter.setString(enabledServicesSetting);
	        while (colonSplitter.hasNext()) {
	            String componentNameString = colonSplitter.next();
	            ComponentName enabledService = ComponentName.unflattenFromString(
	                    componentNameString);
	            if (enabledService != null) {
	                enabledServices.add(enabledService);
	            }
	        }
	        return enabledServices;
	    }
	    public void onPreferenceToggled(String preferenceKey, boolean enabled) {
            // Parse the enabled services.
            Set<ComponentName> enabledServices = getEnabledServicesFromSettings(getActivity());

            // Determine enabled services and accessibility state.
            ComponentName toggledService = ComponentName.unflattenFromString(preferenceKey);
            final boolean accessibilityEnabled;
            if (enabled) {
                // Enabling at least one service enables accessibility.
                accessibilityEnabled = true;
                enabledServices.add(toggledService);
            } else {
                // Check how many enabled and installed services are present.
                int enabledAndInstalledServiceCount = 0;
                Set<ComponentName> installedServices = sInstalledServices;
                for (ComponentName enabledService : enabledServices) {
                    if (installedServices.contains(enabledService)) {
                        enabledAndInstalledServiceCount++;
                    }
                }
                // Disabling the last service disables accessibility.
                accessibilityEnabled = enabledAndInstalledServiceCount > 1
                        || (enabledAndInstalledServiceCount == 1
                        && !installedServices.contains(toggledService));
                enabledServices.remove(toggledService);
            }

            // Update the enabled services setting.
            StringBuilder enabledServicesBuilder = new StringBuilder();
            // Keep the enabled services even if they are not installed since we
            // have no way to know whether the application restore process has
            // completed. In general the system should be responsible for the
            // clean up not settings.
            for (ComponentName enabledService : enabledServices) {
                enabledServicesBuilder.append(enabledService.flattenToString());
                enabledServicesBuilder.append(ENABLED_ACCESSIBILITY_SERVICES_SEPARATOR);
            }
            final int enabledServicesBuilderLength = enabledServicesBuilder.length();
            if (enabledServicesBuilderLength > 0) {
                enabledServicesBuilder.deleteCharAt(enabledServicesBuilderLength - 1);
            }
            MyLog.d(TAG, "enabledServicesBuilder.toString():"+enabledServicesBuilder.toString());
            MyLog.d(TAG, "accessibilityEnabled:"+(accessibilityEnabled?1:0));
            Settings.Secure.putString(getContentResolver(),
                    Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES,
                    enabledServicesBuilder.toString());
            // Update accessibility enabled.
            Settings.Secure.putInt(getContentResolver(),
                    Settings.Secure.ACCESSIBILITY_ENABLED, accessibilityEnabled ? 1 : 0);
        }
}
